<?php
//create a new account for a non existing user
function tb_trser_market_new_user_creation(){
	// create a new user 
	$user_name = sanitize_user( $_POST["tb_trser_market_user_name"], true );
	$user_email = sanitize_text_field($_POST["tb_trser_market_email"]);
	if(!is_email($user_email)){
		wp_die( __("Incorrect email address! Please return to the previous page and enter a valid email!") );
		exit;
	}
	$user_id = username_exists( $user_name );
	if ( !$user_id and email_exists($user_email) == false ) {
		$random_password = wp_generate_password( 12, false );
		$user_id = wp_create_user( $user_name, $random_password, $user_email );
	} else {
		wp_die( __("User name or email already exists! Try another name or email.") );
		exit;
	}
	$creds = array();
	$creds['user_login'] = $user_name;
	$creds['user_password'] = $random_password;
	$creds['remember'] = true;
	$user = wp_signon( $creds, false );
	if ( is_wp_error($user) ){
		wp_die(__("Logon failed!Contact an admin.").$user->get_error_message());
		exit;

	}
	else
	{
		// send welcome mail to the user with the generated password
		tb_trser_market_new_user_create_message($user);
		require_once('tb_trser_market_notification_emails.php');
		wp_mail($user_email, 'Welcome to Linguistic guide', tb_trser_market_customer_mail_new_account($random_password),$headers);
	}
}

// place a message for the new user that has just created the account
function tb_trser_market_new_user_create_message($current_user){
	// print welcome screeen
	add_option( 'tb_trser_market_options_'.$current_user->ID, "1" );
}

// prints the new user welcome message it is only printed one in the lifetime
function tb_trser_market_new_user_print_message(){
	// get the details of the current user
	$current_user = wp_get_current_user();
	// create  a new user 
	if(get_option('tb_trser_market_options_'.$current_user->ID)==false)	{
		// the user is not new do not do anything
		return;
	} else {
		if ( !is_user_logged_in() ) {
			wp_die( __("You are not logged in! You can not create a new message for the new user creation."));
			delete_option('tb_trser_market_options_'.$current_user->ID);
			wp_redirect( site_url().__("/my-orders/"));
		}
		// new user display welcome message
		$html = "<div class=\"notice\"><b>".__("Hello ").$current_user->user_login.",</b></br>";
		$html .= __("You are now logged in and your account has been created.")."</br>";
		$html .= __("Your automaticaly generated password has been transmitted to: ").$current_user->user_email."</br></div></br>";
		// delete that the user is new
		delete_option('tb_trser_market_options_'.$current_user->ID);
		return $html;
	} 
} 
?>